<template>
    <el-form-item class="ckeckedLocation" style="width:25%" >
        <el-checkbox-group v-model="checkAll" @change="handleCheckAllChange">
            <el-checkbox :label="idx">{{opt.name}}</el-checkbox>
        </el-checkbox-group>
        <el-checkbox-group
            v-model="checkIds" @change="handleCheckedChange">
            <el-checkbox v-for="item in opt.child" :label="item.id" :key="item.id" style="margin-left:30px">{{item.name}}</el-checkbox>
        </el-checkbox-group>
   </el-form-item>
</template>
<script>
export default {
    props: {
        opt: {
            type: Object,
            default () {
                return {}
            }
        },
    	idx: Number,
    	checkItems: Array
    },
    data () {
        return {
            checkAll: false,
        	allIds: [],
        	checkIds: [],
            checkItemsObj: this.checkItems,
            oldId: 0
        }
    },
    watch: {
    	checkItems: function(val) {
    		this.checkItemsObj = val
    		this.checkIds = this.getCheck(val)
            let checkedCount = this.checkIds.length
        	this.checkAll = checkedCount === this.allIds.length
        }
    },
    mounted () {
        let ids = []
        this.opt.child.forEach(element => {
          ids.push(element.id)
        })
        this.allIds = ids
    },
    methods: {
    	getCheck: function(vals) {
    		var arr = []
    		if (vals.length > 0) {
	    		var ids = JSON.parse(JSON.stringify(this.allIds))
	    		for(var i=0; i<ids.length; i++){
	    			for(var j=0; j<vals.length; j++) {
	    				if(vals[j] === ids[i]) {
		    				arr.push(vals[j])
	    				}
	    			}
	    		}
    		}
    		return arr
    	},
        handleCheckAllChange (val) {
            this.checkIds = val ? this.allIds : []
             if (this.checkAll) {
	        	this.addIds(this.allIds)
	        } else {
	        	this.delIds(this.allIds)
	        }
            this.$emit('change-check', this.checkItemsObj)
        },
        handleCheckedChange (value) {
            let checkedCount = value.length
            this.checkAll = checkedCount === this.allIds.length
	        this.delIds(this.allIds)
            this.addIds(this.checkIds)
            this.$emit('change-check', this.checkItemsObj)
        },
        delIds: function(ids) {
        	for(var i=0; i<ids.length; i++) {
				for(var j= this.checkItemsObj.length-1; j>-1; j--) {
					if(ids[i] === this.checkItemsObj[j]) {
						this.checkItemsObj.splice(j, 1);
					}
				}
			}
        },
        addIds: function(ids) {
        	this.delIds(ids)
        	this.checkItemsObj = this.checkItemsObj.concat(ids)
        }
    }
}
</script>
